package com.kotlin.hxh.ui.fragment.second.child

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.kotlin.hxh.R
import com.kotlin.hxh.base.BaseBackFragment
import kotlinx.android.synthetic.main.content_detail.*
import kotlinx.android.synthetic.main.fragment_detail.*
import kotlinx.android.synthetic.main.toolbar.*

/**
 * @author huxh
 * @date 2018/12/19.
 */
class DetailFragment : BaseBackFragment() {
    private var mTitle: String? = null

    companion object {
        private val ARG_TITLE = "arg_title"
        private val REQ_MODIFY_FRAGMENT = 100
        @JvmField
        val KEY_RESULT_TITLE = "title"
        @JvmStatic
        fun newInstance(title: String): DetailFragment {
            val fragment = DetailFragment()
            val args = Bundle()
            args.putString(ARG_TITLE, title)
            fragment.arguments = args
            return fragment
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null) {
            mTitle = arguments!!.getString(ARG_TITLE)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = inflater.inflate(R.layout.fragment_detail, container, false)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        toolbar.title = mTitle
        initToolbarNav(toolbar)
    }


    /**
     * 这里演示:
     * 比较复杂的Fragment页面会在第一次start时,导致动画卡顿
     * Fragmentation提供了onEnterAnimationEnd()方法,该方法会在 入栈动画 结束时回调
     * 所以在onCreateView进行一些简单的View初始化(比如 toolbar设置标题,返回按钮; 显示加载数据的进度条等),
     * 然后在onEnterAnimationEnd()方法里进行 复杂的耗时的初始化 (比如FragmentPagerAdapter的初始化 加载数据等)
     */
    override fun onEnterAnimationEnd(savedInstanceState: Bundle?) {
        super.onEnterAnimationEnd(savedInstanceState)
        initDelayView()
    }

    private fun initDelayView() {
        tv_content.setText(R.string.large_text)
        fab.setOnClickListener {
            startForResult(ModifyDetailFragment.newInstance(mTitle), REQ_MODIFY_FRAGMENT)
        }
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        super.onFragmentResult(requestCode, resultCode, data)
        if (requestCode == REQ_MODIFY_FRAGMENT && resultCode == ISupportFragment.RESULT_OK && data != null) {
            mTitle = data.getString(KEY_RESULT_TITLE)
            toolbar.title = mTitle
            arguments?.putString(ARG_TITLE, mTitle)
            Toast.makeText(_mActivity, R.string.modify_title, Toast.LENGTH_LONG).show()
        }
    }
}